package com.tuling.jucdemo.threadbase;

/**
 * 买票小程序测试
 */
public class SellTicketsDemo implements Runnable {
    //车票
    private int tickets;

    public SellTicketsDemo(){
        this.tickets = 1000;
    }

    @Override
    public void run(){
        while(tickets>0){
            synchronized (this){
                if(tickets>0){
                    try {
                        //线程进入休眠期
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 获取到当前正在执行的程序的名称，打印余票
                    System.out.println(Thread.currentThread().getName()+":正在执行操作,余票:"+tickets--);
                }
            }
            Thread.yield();
        }
    }

    public static void main(String[] args) {
        SellTicketsDemo demo = new SellTicketsDemo();

        Thread t1 = new Thread(demo,"t1");
        Thread t2 = new Thread(demo,"t2");
        Thread t3 = new Thread(demo,"t3");
        Thread t4 = new Thread(demo,"t4");

        //priority优先级默认是5，最低1，最高10
        t1.setPriority(Thread.MIN_PRIORITY);
        t2.setPriority(Thread.MAX_PRIORITY);
        t3.setPriority(Thread.MIN_PRIORITY);
        t4.setPriority(Thread.MAX_PRIORITY);

        t1.start();
        t2.start();
        t3.start();
        t4.start();


    }




}
